<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
	<th:block th:include="include :: header('报关单编辑')" />
	<th:block th:include="include :: businessCSS" />
	<style>
        .main-content{position: relative;}
        .topbtns{position:fixed;top: 0;width: 100%;z-index: 9999;background-color: #fff;}
		.preservationBtn{padding: 10px;margin: 0;position: fixed;top: 0;z-index: 9999;background: #fff;width: 100%;}
		.preservationBtn input{font-size: 16px;background-color: rgb(80, 138, 238);color: #fff;border: none;padding: 5px 30px;border-radius: 5px;cursor: pointer;}
		/* .layui-border-box{height: 350px !important;}
		.layui-table-body{height: 240px !important;} */
		.layui-table-tool-temp{padding-right: 30px;}
        .getDetailUpload,.getDetailUpload2{cursor: pointer;}
        .layui-table-tool-self{display: none;}

	</style>
</head>
<body class="no-skin">
<div class="main-container" id="main-container">
	<div class="main-content">
	<form class="layui-form head-form">
		<div class="north">
			<th:block th:include="include :: business_btn" />
			<th:block th:include="include :: business_tp2('top')" />
		</div>
		<div class="mid-content">
            <table class="layui-hide" id="dhtable" lay-filter="dhtable"></table>
            <script type="text/html" id="zjtoolbar">
                <div style="padding: 16px;display: flex;justify-content: space-between;">
                    <div  style="font-weight: 700;font-size: 18px;">物流订单列表</div>
            		<div>
                        <button class="layui-btn layui-btn-normal dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="addbtn" id="btn-sh">新增</button>
                        <button class="layui-btn layui-btn-danger dhicon" th:classappend="${enableEdit} == 1 ?'':'layui-btn-disabled'" type="button" th:disabled="${enableEdit} == 1 ?false:true" lay-event="mjbtn_save" id="btn-sh">删除</button>
            		</div>
            	</div>
            </script>
        </div>
		<div>
			<table class="layui-hide" id="zjdhtable" lay-filter="zjtable"></table>
			<script type="text/html" id="jptoolbar">
				<div style="padding: 16px;display: flex;justify-content: space-between;">
					<div style="font-weight: 700;font-size: 18px;">商品列表</div>
				</div>
			</script>
		</div>
        <th:block th:include="include :: pageFooter" /> 
    </form>
	</div>
</div>

<th:block th:include="include :: footer" />
<th:block th:include="include :: businessJS" />
<th:block th:include="include :: inlineJS" />
<script th:src="@{/dhecp/js/dh-toFixed.js}"></script>


<script th:inline="javascript">
	/*<![CDATA[*/
	var prefix = ctx + "storage/tsCustomsclearance";

	var fields = [[${fields}]];
    var fieldsList = [[${fieldsList}]];
	var fieldsHiddenList = [[${fieldsHiddenList}]];

	var moduleTable = [[${moduleTable}]];
	var enableEdit = [[${enableEdit}]];
    //表格基础信息
	var gridColumns = [[${gridColumns}]];
	//物流订单表格基础信息
	var gridColumnsZJ = [ [
		{type: 'numbers', fixed: 'left'}
		, {type: 'checkbox'}
		,{align: 'center',field: 'code', title: '物流单号'}
		,{align: 'center',field: 'namelogsticsway', title: '物流名称'}
		,{align: 'center',field: 'codelogsticsserver', title: '物流服务商'}
		,{align: 'center',field: 'guidYl', title: '订单原id',hide: true}

	]];
    // 列表数据
    var List=[[${List}]];
    //子件列表数据
    var sonList=[[${sonList}]];
	var listData1=List ?List:[]
	var listData2=sonList ?sonList:[]
	var $,layer,form,table,nid,noTable;

	layui.use(['laydate','form','layer','jquery','util','element','upload','table'], function () {
        $ = layui.$,layer = layui.layer,form = layui.form,laydate = layui.laydate,util = layui.util,element=layui.element,upload = layui.upload,table = layui.table;
        // beforeInit();//表单初始化之前的动作集合
		//初始化操作
		// headcom3()
        nid=$('#nid').val();
         // 保存按钮事件变化
        $(function(){
           $('.tp-save').attr('onclick','')
           $('.tp-save').attr('lay-filter','btn-edit')
           $('.tp-save').attr('lay-submit',true)
        })

        
        // 保存操作
        form.on('submit(btn-edit)', function(data){
            var is_return = false//是否中断保存
            fieldsList.map((v,i)=>{
                if(v.fieldFrontRequired){
                	if (!is_return){
						if(!$('#'+v.fields).val()){
							layer.msg(v.fieldName+'不能为空')
							is_return=true
						}
					}
                }
            })
			if(is_return) return;

			//列表不能为空
			if(listData1.length == 0){
				layer.msg('物流订单列表不能为空');
				return;
			}
			//列表不能为空
			if(listData2.length == 0){
				layer.msg('商品列表不能为空');
				return;
			}

			//详情
			for(var i = 1; i < gridColumns.dictionaryForPageFieldList.length; i++){
				if(gridColumns.dictionaryForPageFieldList[i].fieldFrontRequired){
					//判断是否为空
					if (listData2.some(items => items[gridColumns.dictionaryForPageFieldList[i].fields] == null || items[gridColumns.dictionaryForPageFieldList[i].fields] == ""
							|| items[gridColumns.dictionaryForPageFieldList[i].fields] == undefined)){
						if (gridColumns.dictionaryForPageFieldList[i].fields == 'numPlanDeliver'){
							layer.msg(gridColumns.dictionaryForPageFieldList[i].fieldName+'不能为0');
						} else {
							layer.msg(gridColumns.dictionaryForPageFieldList[i].fieldName+'不能为空');
						}
						is_return=true;
						break;
					}
				}
			}
			if(is_return) return;

			listData2.map((v,i)=>{
                v.iid=i+1
            })

			$.modal.loading("正在处理中，请稍后...");
			$.post("/storage/tsCustomsclearance/editpost",{infoMap:JSON.stringify(data.field),infoItems:JSON.stringify(listData1),sonData: JSON.stringify(listData2)},function(res){
				$.modal.closeLoading()
				layer.msg(res.msg);
				if(res.code == 0){
					window.location.href = '/storage/tsCustomsclearance/edit?nid=' + res.data;
				}
			});
        });

        // 初始化表格
            $.tablelist.init({
                elem: '#dhtable'
                ,data: listData1
                , page: false
                , even: true
                , limit: 10000
                , totalRow: false
                , cols: gridColumnsZJ
                , toolbar: '#zjtoolbar'
                , defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
                , height: '320'
                , done: function (res, curr, count) {
                    listData1 = table.cache.dhtable;//每次重载都赋值更新表缓存
					fixTotal(this);//修复合计行固定列问题
					rowheight(res, curr);//修复合计行固定列问题
					detailUpload();
                },success:function(a,b,c){
                        console.log(a,b,c)
                }
            });

		$.tablelist.init({
			elem: '#zjdhtable'
			, data: listData2
			, page: false
			, even: true
			, limit: 10000
			, totalRow: gridColumns.totalRow
			, cols: [gridColumns.gridBody]
			, toolbar: '#jptoolbar'
			, defaultToolbar: [{title: '列设置', layEvent: 'fieldSet', icon: 'layui-icon-set'}]
			, height: '300'
			, done: function (res, curr, count) {
				listData2 = table.cache.zjdhtable;//每次重载都赋值更新表缓存
			}
		});

		//监听单元格编辑
		table.on('edit(zjtable)', function (obj) {
			var regular2 = /^[0-9]+(.[0-9]{0,2})?$/
			var tr = obj.tr;
			// 单元格编辑之前的值
			var oldtext = $(tr).find("td[data-field='"+obj.field+"'] div").text();
			let fxa = true;
			listData2.map((v, i) => {
				if(fxa){
					if (!regular2.test(obj.value) && obj.value != '') {
						v[obj.field]  = oldtext;
						fxa = false
						return
					}
				}
			})
			if (!fxa){
				layer.msg("商品单价只允许输入两位小数点的正数,请核实后在操作!")
			}
			calculation()
		});

        //商品表格操作
        table.on('toolbar(dhtable)', function (obj) {
            var selectedObject=""
            sessionStorage.setItem('dhtable',JSON.stringify(table.cache.dhtable))
            table.cache.dhtable.map((v,i)=>{
                if(selectedObject){
                    selectedObject+=','+v.code
                }else{
                    selectedObject+=v.code
                }
            })
            switch (obj.event) {
                case 'addbtn':
					if ($('#codelogsticsserver').val() == ''){
						layer.msg('物流服务商未填写,请填写后在操作!');
						return
					}

					if ($('#destinationfulfillmentcenterid').val() == ''){
						layer.msg('亚马逊仓库未填写,请填写后在操作!');
						return
					}
			    layer.open({
                	type: 2,
                	area: [($(window).width() - 200)+'px', ($(window).height() - 100)+'px'],
                	fix: false,//不固定
                	offset: '10%',//距离顶部
                	maxmin: true,//最大最小化
                	shade: 0.3,//遮罩
                	title: '物流列表',
					content: "/storage/tsCustomsclearance/select2?pagetype=checkbox&by=direct"+"&selectedObject="+selectedObject+"&codelogsticsserver="+$('#codelogsticsserver').val()+"&destinationfulfillmentcenterid="+$('#destinationfulfillmentcenterid').val()+"&bid="+$('#bid').val(),
					btn: ['确定', '取消'],
                	shadeClose: true,// 弹层外区域关闭
                	yes: function(index, layero){
						var res = window["layui-layer-iframe" + index].callbackdata();
						if(res.length > 0){
							layer.closeAll();
                            var mjdata=sessionStorage.getItem('dhtable')
                            if(mjdata){
                                mjdata=JSON.parse(mjdata)
                                let newall=[]
                                let endData = [];
                                var isdata=false
                                for (let i = 0; i < res.length; i++) {
                                    var isdata=false
                                    if (newall.indexOf(res[i].code) === -1) {
                                        for (let n = 0; n < mjdata.length; n++) {
                                            if (newall.indexOf(res[i].code) === -1) {
                                                if(res[i].code==mjdata[n].code){
                                                   isdata=true
                                                   endData.push(mjdata[n]);
                                                   newall.push(mjdata[n].code);
                                                }
                                            }
                                        }
                                        if(!isdata){
                                            endData.push(res[i]);
                                            newall.push(res[i].code);
                                        }
                                    }
                                }
								table.reload('dhtable', {data:endData});
                            }else{
                                table.reload('dhtable', {data:res});
                            }
							$.post("/storage/tsCustomsclearance/list3",{res:JSON.stringify(res)},function(ress){
								listData2 = ress.data
								calculation()
							});
				        }else{
                            layer.msg("请选择数据");
                        }
                	}
                });

                   break;

                case 'mjbtn_save':
                    var objdata=table.checkStatus('dhtable')
                    objdata=objdata.data
                    listData1= table.cache.dhtable;
					listData2 = table.cache.zjdhtable;
                    if(objdata.length>0){
                        objdata.forEach(item => {
                        	//根据code删除
                            listData1 = listData1.filter(items => items.code!= item.code);
                        });
						objdata.forEach(item => {
							listData2 = listData2.filter(items => items.logisticsorder != item.code);
						});
						table.reload('dhtable', {data: listData1});
						table.reload('zjdhtable', {data: listData2});
						calculation()
					}else{
                        layer.msg("请选择数据");
                    }
                    break;
            };
        });
    });

	// 根据商品列表计算计算总值
	function calculation() {
		//整票毛重(kg)
		var roughweight = 0;
		//整票净重(kg)
		var netweight = 0;
		//报关总金额
		var amountdeclared = 0;
		//总箱数取最后一条的数据
		var numbox = 0;
		listData2.map((v, i) => {
			roughweight = roughweight + v.weightreal
			netweight = netweight + (v.netweight)
			//重新计算报关单价
			v.bgprice =  (v.price2 * 1.02).toFixed(2)
			v.bgtolprice = (v.bgprice * v.quantityshipped).toFixed(2)
			amountdeclared = parseFloat(amountdeclared)+ parseFloat(v.bgtolprice);
			numbox = v.numbox
		});
		$('#roughweight').val(roughweight.toFixed(2))
		$('#netweight').val(netweight.toFixed(2))
		$('#amountdeclared').val(amountdeclared.toFixed(2))
		$('#numbox').val(numbox)
		table.reload('zjdhtable', {data: listData2});
	}

    /**
     * 回调弹框事件
     */
    function getMoreAfter(fieldsList,fields,tindex,fieldName,fieldSearchType,isSearch,isLayer,res) {//弹出框赋值回调
		if(fields=='destinationfulfillmentcenterid'){
			table.reload('dhtable', {data: []});
			table.reload('zjdhtable', {data: []});
			$('#destinationaddress').val(res.addressLine1 + ',' + res.postalCode + '-' + res.city+ ',' + res.stateOrProvinceCode);
		}
		if(fields=='codelogsticsserver'){
			table.reload('dhtable', {data: []});
			table.reload('zjdhtable', {data: []});
		}
	}

</script>

</body>
</html>